package com.imooc.miaosha.controller;

import com.imooc.miaosha.dao.OrderDao;
import com.imooc.miaosha.pojo.ApiResultTo;
import com.imooc.miaosha.pojo.CodeMsg;
import com.imooc.miaosha.pojo.domain.MiaoshaUser;
import com.imooc.miaosha.pojo.domain.OrderInfo;
import com.imooc.miaosha.pojo.vo.GoodsVo;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/miaosha")
public class MiaoshaController {
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderDao orderDao;
    @Autowired
    MiaoshaService miaoshaService;

    /**
     * 这应该算是核心业务，实现秒杀功能
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/do_miaosha",method = RequestMethod.POST)
    public ApiResultTo<?> doMiaosha(MiaoshaUser user, @RequestParam long goodsId){
        if (ObjectUtils.isEmpty(user))
            ApiResultTo.buildFailed(CodeMsg.USER_NOT_LOGIN);
        //判断库存
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        int stock = goodsVo.getGoodsStock();
        if (stock <= 0)
            return ApiResultTo.buildFailed(CodeMsg.STOCK_EMPTY);
        //判断是否已经秒杀到了
        OrderInfo orderInfo = orderDao.findByUserIdAndGoodsId(user.getId(), goodsId);
        if (orderInfo != null) return ApiResultTo.buildFailed(CodeMsg.ORDER_REPEAT);

        /*减库存、下订单，写入秒杀订单
        * 这三部应该在一个事务里边完成！保证原子性*/
        OrderInfo info = miaoshaService.miaosha(user,goodsVo);
        return ApiResultTo.buildSuccess(info);





    }
}
